package org.lds.hotkey.common.util;

import io.etcd.jetcd.KeyValue;
import io.etcd.jetcd.watch.WatchEvent;
import org.apache.commons.lang3.StringUtils;
import org.lds.hotkey.common.model.Entity;

import java.util.Objects;

public class EntityModelUtil {
    public static Entity getEntity(String etcdKey) {
        if (StringUtils.isEmpty(etcdKey)) return null;

        String[] splitKey = etcdKey.split("/");
        int length = splitKey.length;
        if (length < 3) return null;

        String appId = splitKey[length - 2];
        String entityId = splitKey[length - 1];
        return Entity.builder()
                .appId(Long.valueOf(appId))
                .id(Long.valueOf(entityId))
                .build();
    }

    public static <T> Entity<T> getEntity(KeyValue keyValue, Class<T> clazz) {
        String key = keyValue.getKey().toString();
        String value = keyValue.getValue().toString();

        Entity entity = getEntity(key);
        if (Objects.isNull(entity)) return null;

        entity.setKey(key);

        T t = JsonUtil.fromJson(value, clazz);
        if (Objects.isNull(t)) return null;
        entity.setValue(t);

        return entity;
    }

    public static <T> Entity<T> getEntity(WatchEvent event, Class<T> clazz) {
        WatchEvent.EventType eventType = event.getEventType();
        if (eventType == WatchEvent.EventType.UNRECOGNIZED) return null;

        KeyValue keyValue = eventType == WatchEvent.EventType.PUT ? event.getKeyValue() : event.getPrevKV();
        return getEntity(keyValue, clazz);
    }

}
